/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package agenda.tela;

import agenda.bean.Cidade;
import agenda.bean.Cliente;
import agenda.controle.ControleCliente;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author Xand
 */
public class TelaCliente extends javax.swing.JFrame {
    private ControleCliente controle;

    /** Creates new form TelaCliente */
    public TelaCliente() {
        controle = new ControleCliente();
        initComponents();
        // adicionar o evendo no combo.
        tCidade.getEditor().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String filtro = "upper(nome) like upper('%"+
                                tCidade.getEditor().getItem()+"%')";
                carregaCidades(filtro);
            }
        });
        limpa();
    }

    private void mostra(Cliente c) {
        tId.setValue(c.getId());
        tNome.setText(c.getNome());
        tCPF.setText(c.getCpf());
        tEndereco.setText(c.getEndereco());
        if (c.getCidade() != null) {
            carregaCidades("id = " + c.getCidade().getId());
        } else {
            carregaCidades(" 1=1 ");
            tCidade.setSelectedIndex(-1);
        }
        tCidade.setSelectedItem(c.getCidade());
        tLimiteCredito.setValue(c.getLimitecredito());
    }

    private Cliente getCliente() {
        Cliente c = new Cliente();
        if (tId.getValue() == null) {
            c.setId(0);
        } else {
            c.setId(Integer.parseInt(tId.getValue().toString()));
        }
        c.setNome(tNome.getText());
        c.setCpf(tCPF.getText());

        c.setEndereco(tEndereco.getText());
        Object obj = tCidade.getSelectedItem();
        if (obj instanceof Cidade) {
            c.setCidade((Cidade)obj);
        }
        if (tLimiteCredito.getValue() != null) {
            c.setLimitecredito(new BigDecimal(tLimiteCredito.getValue().toString()));
        } else {
            c.setLimitecredito(null);
        }
        return c;
    }

    private void limpa() {
        tId.setValue(null);
        tNome.setText("");
        tCPF.setValue(null);
        tEndereco.setText("");
        carregaCidades(" 1=1 ");
        tCidade.setSelectedIndex(-1);
        tLimiteCredito.setValue(null);
    }

    private void carregaCidades(String filtro) {
        List<Cidade> cidades = controle.carregaCidades(filtro);
        tCidade.removeAllItems();
        for (Cidade cidade : cidades) {
            tCidade.addItem(cidade);
        }
        if (!cidades.isEmpty()) {
            tCidade.setSelectedIndex(0);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        calendarFactory1 = new net.sf.nachocalendar.CalendarFactory();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        bPesquisar = new javax.swing.JButton();
        bLimpar = new javax.swing.JButton();
        bGravar = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();
        bExcluir = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        tLimiteCredito = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        tCidade = new javax.swing.JComboBox();
        bPesquisaCidade = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        tEndereco = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        tCPF = new javax.swing.JFormattedTextField();
        jPanel6 = new javax.swing.JPanel();
        tNome = new javax.swing.JTextField();
        jPanel7 = new javax.swing.JPanel();
        tId = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cadastro de Cliente");
        setMinimumSize(new java.awt.Dimension(518, 402));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Cadastro de Cliente");

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        bPesquisar.setText("Pesquisar");
        bPesquisar.setMargin(new java.awt.Insets(2, 0, 2, 0));
        bPesquisar.setPreferredSize(new java.awt.Dimension(90, 20));
        bPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPesquisarActionPerformed(evt);
            }
        });

        bLimpar.setText("Limpar");
        bLimpar.setMargin(new java.awt.Insets(2, 0, 2, 0));
        bLimpar.setPreferredSize(new java.awt.Dimension(90, 20));
        bLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bLimparActionPerformed(evt);
            }
        });

        bGravar.setText("Gravar");
        bGravar.setMargin(new java.awt.Insets(2, 0, 2, 0));
        bGravar.setPreferredSize(new java.awt.Dimension(90, 20));
        bGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGravarActionPerformed(evt);
            }
        });

        bCancelar.setText("Cancelar");
        bCancelar.setMargin(new java.awt.Insets(2, 0, 2, 0));
        bCancelar.setPreferredSize(new java.awt.Dimension(90, 20));
        bCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelarActionPerformed(evt);
            }
        });

        bExcluir.setText("Excluir");
        bExcluir.setMargin(new java.awt.Insets(2, 0, 2, 0));
        bExcluir.setPreferredSize(new java.awt.Dimension(90, 20));
        bExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(bPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bGravar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bGravar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Limite de credito"));
        jPanel2.setLayout(new java.awt.BorderLayout());

        tLimiteCredito.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
        tLimiteCredito.setPreferredSize(new java.awt.Dimension(90, 20));
        jPanel2.add(tLimiteCredito, java.awt.BorderLayout.CENTER);

        jLabel7.setText("Alexandre Magri");

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Cidade"));
        jPanel3.setLayout(new java.awt.BorderLayout(4, 0));

        tCidade.setEditable(true);
        tCidade.setPreferredSize(new java.awt.Dimension(90, 20));
        jPanel3.add(tCidade, java.awt.BorderLayout.CENTER);

        bPesquisaCidade.setText("...");
        bPesquisaCidade.setPreferredSize(new java.awt.Dimension(30, 20));
        bPesquisaCidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPesquisaCidadeActionPerformed(evt);
            }
        });
        jPanel3.add(bPesquisaCidade, java.awt.BorderLayout.EAST);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Endereço"));
        jPanel4.setLayout(new java.awt.BorderLayout());

        tEndereco.setPreferredSize(new java.awt.Dimension(90, 20));
        jPanel4.add(tEndereco, java.awt.BorderLayout.CENTER);

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("CPF"));
        jPanel5.setLayout(new java.awt.BorderLayout());

        try {
            tCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jPanel5.add(tCPF, java.awt.BorderLayout.CENTER);

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Nome"));
        jPanel6.setLayout(new java.awt.BorderLayout());
        jPanel6.add(tNome, java.awt.BorderLayout.CENTER);

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("ID"));
        jPanel7.setLayout(new java.awt.BorderLayout());

        tId.setBorder(null);
        tId.setEditable(false);
        tId.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tId.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        tId.setPreferredSize(new java.awt.Dimension(90, 20));
        jPanel7.add(tId, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel7)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void bPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPesquisarActionPerformed
        Cliente c = controle.pesquisar();
        mostra(c);
    }//GEN-LAST:event_bPesquisarActionPerformed

    private void bLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bLimparActionPerformed
        limpa();
        tNome.requestFocus();
    }//GEN-LAST:event_bLimparActionPerformed

    private void bGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGravarActionPerformed
        Cliente c = getCliente();
        if (controle.gravar(c)) {
            JOptionPane.showMessageDialog(null, "Cliente Gravado com Sucesso!");
            tId.setValue(c.getId());
        } else {
            JOptionPane.showMessageDialog(null, "Erro ao Gravar!");
        }
    }//GEN-LAST:event_bGravarActionPerformed

    private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
        Cliente c = getCliente();
        if (c.getId() > 0) {
            c = controle.carregaCliente(c.getId());
            mostra(c);
        } else {
            limpa();
        }
    }//GEN-LAST:event_bCancelarActionPerformed

    private void bExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bExcluirActionPerformed
        Cliente c = getCliente();
        if (controle.excluir(c.getId())) {
            JOptionPane.showMessageDialog(null, "Excluido com Sucesso!");
            limpa();
        } else {
            JOptionPane.showMessageDialog(null, "Erro ao Excluir!");
        }
    }//GEN-LAST:event_bExcluirActionPerformed

    private void bPesquisaCidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPesquisaCidadeActionPerformed
        Cidade c = controle.pesquisaCidade();
        tCidade.removeAllItems();
        tCidade.addItem(c);
        tCidade.setSelectedItem(c);
    }//GEN-LAST:event_bPesquisaCidadeActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaCliente().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCancelar;
    private javax.swing.JButton bExcluir;
    private javax.swing.JButton bGravar;
    private javax.swing.JButton bLimpar;
    private javax.swing.JButton bPesquisaCidade;
    private javax.swing.JButton bPesquisar;
    private net.sf.nachocalendar.CalendarFactory calendarFactory1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JFormattedTextField tCPF;
    private javax.swing.JComboBox tCidade;
    private javax.swing.JTextField tEndereco;
    private javax.swing.JFormattedTextField tId;
    private javax.swing.JFormattedTextField tLimiteCredito;
    private javax.swing.JTextField tNome;
    // End of variables declaration//GEN-END:variables

}
